<template>
  <el-drawer v-model="isDrawerShow" :title="drawerTitle" @closed="handleDrawerClosed" @open="handleDrawerOpen">
    <template #default>
      <el-form ref="formRef" :model="salaryGroup" :rules="rules">
        <el-form-item v-if="salaryGroup.salarygroup_id !== undefined" label="ID" prop="salaryitem_id">
          <el-text>{{ salaryGroup.salarygroup_id }}</el-text>
        </el-form-item>
        <el-form-item label="名称" prop="salarygroup_name">
          <el-input v-model="salaryGroup.salarygroup_name"/>
        </el-form-item>
        <el-form-item label="薪资项" prop="salary_list">
          <salary-item-selector v-model="salaryGroup.salary_list" type="salaryItems"/>
        </el-form-item>
        <el-form-item label="人员" prop="userid_list">
          <employee-table-for-select
              ref="employeeTableForSelectRef"
              v-model="salaryGroup.userid_list"
              :init-selected="initUsers"
              type="userIds"
          />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button type="primary" @click="handleConfirmClick">确定</el-button>
      <el-button @click="handleCancelClick">取消</el-button>
    </template>
  </el-drawer>
</template>
<script lang="ts" setup>
import {computed, ref, useTemplateRef} from "vue";
import {ElForm, ElMessage, FormRules} from "element-plus";
import {isAxiosError} from "axios";
import {addSalaryGroup, updateSalaryGroup} from "@/api/salaryGroup";
import EmployeeTableForSelect from "@/components/table/EmployeeTableForSelect.vue";
import SalaryItemSelector from "@/components/selector/SalaryItemSelector.vue";

const salaryGroup = ref<SalaryGroupRequest>({})
const isDrawerShow = defineModel<boolean>()
const props = defineProps<{
  initUsers?: { departmentId: number, userId: string }[],
  salaryGroupToEdit?: SalaryGroupRequest
}>()
const emit = defineEmits<{
  addSuccess: []
  success: []
  updateSuccess: []
}>()
const drawerTitle = computed(() => salaryGroup.value.salarygroup_id === undefined ? "新增薪资组" : "修改薪资组")
const formRef = ref<InstanceType<typeof ElForm>>()
const employeeTableForSelectRef = useTemplateRef<InstanceType<typeof EmployeeTableForSelect>>("employeeTableForSelectRef")

const rules: FormRules = {
  salarygroup_name: [
    {
      required: true,
      message: "名称不能为空",
      trigger: "blur"
    }
  ],
  salary_list: [
    {
      required: true,
      message: "薪资项不能为空",
      trigger: "change"
    }
  ],
  userid_list: [
    {
      required: true,
      message: "人员不能为空",
      trigger: "change"
    }
  ]
}

function handleCancelClick() {
  isDrawerShow.value = false
}

function handleConfirmClick() {
  formRef.value?.validate(async (isValid) => {
    if (isValid) {
      try {
        if (salaryGroup.value.salarygroup_id === undefined) {
          const {code, msg} = await addSalaryGroup(salaryGroup.value)
          if (code === "200") {
            ElMessage.success(msg)
            emit("addSuccess")
          } else {
            ElMessage.error(msg)
          }
        } else {
          const {code, msg} = await updateSalaryGroup(salaryGroup.value)
          if (code === "200") {
            ElMessage.success(msg)
            emit("updateSuccess")
          } else {
            ElMessage.error(msg)
          }
        }
        isDrawerShow.value = false;
        emit("success")
      } catch (error) {
        if (isAxiosError(error) && error.response?.data.message != undefined) {
          ElMessage.error(error.response?.data.message);
        }
      }
    }
  })
}

function handleDrawerClosed() {
  formRef.value?.resetFields()
  employeeTableForSelectRef.value?.clearDepartmentSelection()
  employeeTableForSelectRef.value?.clearEmployeesToBeSelected()
  salaryGroup.value = {}
}

function handleDrawerOpen() {
  if (props.salaryGroupToEdit !== undefined) {
    salaryGroup.value = props.salaryGroupToEdit
  }
}
</script>
